package com.example.zjx8969.myapplication;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LiveDataRepository<T> {
    public static OkHttpClient client;

    static {
        client = new OkHttpClient.Builder().build();
    }

    public LiveData<T> getData(String url) {
        final MutableLiveData<T> liveData = new MutableLiveData<T>() {
        };
        Request.Builder builder = new Request.Builder().url(url).tag(url);
        client.newCall(builder.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                liveData.postValue(null);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                liveData.postValue((T) response.body().string());
            }
        });
        return liveData;
    }
}
